package com.zzyl.nursing.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.function.BiConsumer;

import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.IotMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;

/**
 * 设备数据Service业务层处理
 * 
 * @author sumu
 * @date 2025-08-04
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 新增设备到数据库
     */
    @Override
    public void batchInsert(IotMsgNotifyData data) {
        //1、设备数据
        //1.1根据设备ID获取设备信息device_id
        String iotId = data.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (device==null){
            return;
        }
        //1.2将设备设备信息赋值到DeviceData中
        //2、上报数据
        ArrayList<DeviceData> list = new ArrayList<>();
        //2.1遍历services
        List<IotMsgService> services = data.getBody().getServices();
        services.forEach(s->{
            //2.2提取services单个对象信息
            //String serviceId = s.getServiceId();
            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(s.getEventTime(),"yyyyMMdd'T'HHmmss'Z'");
                    LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                            .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                            .toLocalDateTime();
            //2.3properties中的每个属性都需要封装成DeviceData
            s.getProperties().forEach((key, value) -> {
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setFunctionId(key);
                //deviceData.setId(null);
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(alarmTime);
                list.add(deviceData);
            });
        });
        //3、批量新增
        saveBatch(list);
    }

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        IPage<DeviceData> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        IPage<DeviceData> page1 = deviceDataMapper.selectPage(page, Wrappers.<DeviceData>lambdaQuery()
                //1、设备名字查询
                .eq(ObjectUtil.isNotEmpty(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                //2功能ID、
                .eq(ObjectUtil.isNotEmpty(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                //3、数据上报时间{开始时间和结束时间}
                .between(ObjectUtil.isAllNotEmpty(dto.getStartTime(), dto.getEndTime()), DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime()));
        TableDataInfo<DeviceData> dataInfo = new TableDataInfo<>();
        dataInfo.setCode(HttpStatus.SUCCESS);
        dataInfo.setRows(page1.getRecords());
        dataInfo.setTotal(page1.getTotal());
        return dataInfo;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        deviceData.setCreateTime(DateUtils.getNowDate());
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        deviceData.setUpdateTime(DateUtils.getNowDate());
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }
}
